<template>
  <div class="price-tools-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>价格管理工具</h2>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索商品名称"
              clearable
              @clear="handleSearch"
              @input="handleSearch"
              style="width: 200px; margin-right: 10px;"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
            <el-button type="primary" @click="fetchProductPrices">刷新</el-button>
            <el-button type="success" @click="fixAllPrices">统一所有商品价格</el-button>
          </div>
        </div>
      </template>
      
      <div class="price-table-container">
        <el-table
          v-loading="loading"
          :data="productPrices"
          border
          style="width: 100%"
          max-height="650"
        >
          <el-table-column prop="productName" label="商品名称" width="180" fixed="left" />
          <el-table-column prop="standardPrice" label="标准价格" width="100" fixed="left">
            <template #default="{ row }">
              {{ row.standardPrice }} 元
            </template>
          </el-table-column>
          
          <el-table-column v-for="channel in channels" :key="channel.id" :label="channel.name" min-width="150">
            <template #default="{ row }">
              <div class="channel-price-cell">
                <span>{{ getChannelPrice(row, channel.id) }} 元</span>
                <el-button type="primary" link size="small" @click="openPriceDialog(row, channel)">
                  修改
                </el-button>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="openUnifyPriceDialog(row)">统一价格</el-button>
            </template>
          </el-table-column>
          
          <template #empty>
            <div class="empty-data">
              <p v-if="loading">正在加载数据...</p>
              <p v-else>暂无数据</p>
              <el-button v-if="!loading" type="primary" @click="fetchProductPrices">重新加载</el-button>
            </div>
          </template>
        </el-table>
      </div>
    </el-card>
    
    <!-- 修改单个渠道价格对话框 -->
    <el-dialog
      v-model="priceDialog.visible"
      :title="`修改 ${priceDialog.productName} 在 ${priceDialog.channelName} 的价格`"
      width="30%"
    >
      <el-form :model="priceDialog.form" label-width="100px">
        <el-form-item label="当前价格">
          <span>{{ priceDialog.currentPrice }} 元</span>
        </el-form-item>
        <el-form-item label="新价格">
          <el-input-number v-model="priceDialog.form.price" :min="0" :precision="2" :step="0.1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="priceDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="updateChannelPrice">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 统一商品价格对话框 -->
    <el-dialog
      v-model="unifyDialog.visible"
      :title="`统一 ${unifyDialog.productName} 在所有渠道的价格`"
      width="30%"
    >
      <el-form :model="unifyDialog.form" label-width="100px">
        <el-form-item label="标准价格">
          <span>{{ unifyDialog.standardPrice }} 元</span>
        </el-form-item>
        <el-form-item label="统一价格">
          <el-input-number v-model="unifyDialog.form.price" :min="0" :precision="2" :step="0.1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="unifyDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="setUnifiedPrice">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 统一所有商品价格确认对话框 -->
    <el-dialog
      v-model="fixAllDialog.visible"
      title="统一所有商品价格"
      width="40%"
    >
      <div class="fix-all-dialog-content">
        <el-alert
          title="此操作将统一所有商品在各渠道的价格"
          type="warning"
          description="对于每个商品，系统将选择其在各渠道中的最低价格作为统一价格，并将该价格应用到所有渠道。此操作不可撤销，请谨慎操作。"
          show-icon
          :closable="false"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="fixAllDialog.visible = false">取消</el-button>
          <el-button type="danger" @click="confirmFixAllPrices">确认统一</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import api from '@/api/index';
import { Search } from '@element-plus/icons-vue';

export default {
  name: 'PriceTools',
  components: {
    Search
  },
  setup() {
    const loading = ref(false);
    const productPrices = ref([]);
    const channels = ref([]);
    const searchQuery = ref('');
    
    // 检查数据是否为空
    const isEmpty = computed(() => {
      return productPrices.value.length === 0;
    });
    
    // 修改单个渠道价格对话框
    const priceDialog = ref({
      visible: false,
      productId: null,
      productName: '',
      channelId: null,
      channelName: '',
      currentPrice: 0,
      form: {
        price: 0
      }
    });
    
    // 统一商品价格对话框
    const unifyDialog = ref({
      visible: false,
      productId: null,
      productName: '',
      standardPrice: 0,
      form: {
        price: 0
      }
    });
    
    // 统一所有商品价格确认对话框
    const fixAllDialog = ref({
      visible: false
    });
    
    // 获取商品价格列表
    const fetchProductPrices = async () => {
      loading.value = true;
      try {
        const params = {};
        if (searchQuery.value) {
          params.productName = searchQuery.value;
        }
        
        console.log('正在请求价格数据，参数:', params);
        
        // 使用导入的api实例
        const response = await api.get('/price-tools/list', { params });
        console.log('价格数据响应:', response);
        
        if (response.data.success) {
          productPrices.value = response.data.data.products || [];
          channels.value = response.data.data.channels || [];
        } else {
          console.error('获取价格数据失败:', response.data);
          ElMessage.error(response.data.message || '获取价格数据失败');
        }
      } catch (error) {
        console.error('获取价格数据出错:', error);
        console.error('错误详情:', error.response || error.message);
        ElMessage.error('获取价格数据失败: ' + (error.response?.data?.message || error.message));
      } finally {
        loading.value = false;
      }
    };
    
    // 搜索商品
    const handleSearch = () => {
      fetchProductPrices();
    };
    
    // 获取渠道价格
    const getChannelPrice = (product, channelId) => {
      const channelPrice = product.channelPrices.find(cp => cp.channelId === channelId);
      return channelPrice && channelPrice.price !== null ? channelPrice.price : '未设置';
    };
    
    // 打开修改价格对话框
    const openPriceDialog = (product, channel) => {
      const channelPrice = product.channelPrices.find(cp => cp.channelId === channel.id);
      const currentPrice = channelPrice && channelPrice.price !== null ? channelPrice.price : product.standardPrice;
      
      priceDialog.value = {
        visible: true,
        productId: product.productId,
        productName: product.productName,
        channelId: channel.id,
        channelName: channel.name,
        currentPrice,
        form: {
          price: currentPrice
        }
      };
    };
    
    // 更新渠道价格
    const updateChannelPrice = async () => {
      try {
        const { productId, channelId, form } = priceDialog.value;
        
        // 构建请求参数
        const data = {
          productId,
          price: form.price
        };
        
        // 调用后端API更新价格
        const response = await api.post(`/channels/${channelId}/prices`, data);
        
        if (response.data.success) {
          ElMessage.success('价格更新成功');
          priceDialog.value.visible = false;
          fetchProductPrices(); // 刷新数据
        } else {
          ElMessage.error(response.data.message || '价格更新失败');
        }
      } catch (error) {
        console.error('更新价格出错:', error);
        ElMessage.error('更新价格失败: ' + (error.response?.data?.message || error.message));
      }
    };
    
    // 打开统一价格对话框
    const openUnifyPriceDialog = (product) => {
      unifyDialog.value = {
        visible: true,
        productId: product.productId,
        productName: product.productName,
        standardPrice: product.standardPrice,
        form: {
          price: product.standardPrice
        }
      };
    };
    
    // 设置统一价格
    const setUnifiedPrice = async () => {
      try {
        const { productId, form } = unifyDialog.value;
        
        // 构建请求参数
        const data = {
          productId,
          price: form.price
        };
        
        // 调用后端API设置统一价格
        const response = await api.post('/price-tools/set-price', data);
        
        if (response.data.success) {
          ElMessage.success(response.data.message || '价格统一设置成功');
          unifyDialog.value.visible = false;
          fetchProductPrices(); // 刷新数据
        } else {
          ElMessage.error(response.data.message || '价格统一设置失败');
        }
      } catch (error) {
        console.error('设置统一价格出错:', error);
        ElMessage.error('设置统一价格失败: ' + (error.response?.data?.message || error.message));
      }
    };
    
    // 打开统一所有商品价格对话框
    const fixAllPrices = () => {
      fixAllDialog.value.visible = true;
    };
    
    // 确认统一所有商品价格
    const confirmFixAllPrices = async () => {
      try {
        loading.value = true;
        
        // 调用后端API统一所有商品价格
        const response = await api.post('/price-tools/fix-all-prices');
        
        if (response.data.success) {
          ElMessage.success(response.data.message || '所有商品价格已统一');
          fixAllDialog.value.visible = false;
          fetchProductPrices(); // 刷新数据
        } else {
          ElMessage.error(response.data.message || '统一价格失败');
        }
      } catch (error) {
        console.error('统一价格出错:', error);
        ElMessage.error('统一价格失败: ' + (error.response?.data?.message || error.message));
      } finally {
        loading.value = false;
      }
    };
    
    onMounted(() => {
      fetchProductPrices();
    });
    
    return {
      loading,
      productPrices,
      channels,
      searchQuery,
      isEmpty,
      priceDialog,
      unifyDialog,
      fixAllDialog,
      fetchProductPrices,
      handleSearch,
      getChannelPrice,
      openPriceDialog,
      updateChannelPrice,
      openUnifyPriceDialog,
      setUnifiedPrice,
      fixAllPrices,
      confirmFixAllPrices
    };
  }
};
</script>

<style scoped>
.price-tools-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.price-table-container {
  margin-top: 20px;
  overflow-x: auto;
}

.channel-price-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.fix-all-dialog-content {
  margin: 20px 0;
}

.empty-data {
  padding: 30px 0;
  text-align: center;
}

.empty-data p {
  margin-bottom: 15px;
  color: #909399;
  font-size: 14px;
}
</style> 